define(['jquery', 'bootstrap', 'backend', 'table', 'form','selectpage'], function ($, undefined, Backend, Table, Form, SelectPage) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'clothmaking_recipe/index' + location.search,
                    add_url: 'clothmaking_recipe/add',
                    edit_url: 'clothmaking_recipe/edit',
                    del_url: 'clothmaking_recipe/del',
                    multi_url: 'clothmaking_recipe/multi',
                    import_url: 'clothmaking_recipe/import',
                    table: 'clothmaking_recipe',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), operate: 'LIKE'},
                        {field: 'parentid', title: __('Parentid')},
                        {field: 'content', title: __('Content'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'recipe_performance', title: __('recipe_performance'), operate: 'LIKE'},
                        {field: 'head_id', title: __('Head_id'), operate: 'EQUALS', formatter: function(value, row, index) {
                            // 显示负责人姓名
                            if (row.head_info && row.head_info.nickname) {
                                return row.head_info.nickname;
                            }
                            return value;
                        }},
                        {field: 'locked', title: __('Locked')},
                        // {field: 'kettle_id', title: __('Kettle_id')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.bindIngredientEvent();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.bindIngredientEvent();
            // 加载已有的配料数据
            Controller.api.loadExistingIngredients();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function(data, ret) {
                    // 成功回调
                    return true;
                }, function(data, ret) {
                    // 失败回调
                    return false;
                }, function(form) {
                    // 提交前回调 - 修改为直接使用名称作为键
                    console.log('FastAdmin提交前回调触发');
                    
                    var ingredientsObj = {};
                    var hasValidIngredients = false;
            
                    // 收集所有配料数据
                    console.log('开始收集配料数据，配料行数量:', $('#ingredient-container .ingredient-row').length);
                    
                    $('#ingredient-container .ingredient-row').each(function(index) {
                        var $row = $(this);
                        var ingredientName = $row.find('.selectpage').val(); // 直接获取显示的名称
                        var quantity = $row.find('input[name*="[quantity]"]').val();
                        
                        console.log('配料行 [索引:', index, '] 名称:', ingredientName, '数量:', quantity);
            
                        if (ingredientName && quantity && quantity > 0) {
                            ingredientsObj[ingredientName] = parseFloat(quantity);
                            hasValidIngredients = true;
                            console.log('有效配料:', ingredientName, '数量:', parseFloat(quantity));
                        } else {
                            console.warn('配料数据不完整 [索引:', index, ']:', ingredientName, quantity);
                        }
                    });
            
                    console.log('收集到的配料对象:', ingredientsObj);
                    console.log('有效配料数量:', Object.keys(ingredientsObj).length);
            
                    if (!hasValidIngredients) {
                        Toastr.error('请至少添加一个有效的配料');
                        return false;
                    }
            
                    // 添加JSON格式的配料数据到表单
                    var ingredientsJson = JSON.stringify(ingredientsObj);
                    console.log('JSON字符串:', ingredientsJson);
                    
                    $('<input>').attr({
                        type: 'hidden',
                        name: 'row[ingredient_details]',
                        value: ingredientsJson
                    }).appendTo('form[role=form]');
            
                    return true;
                });
            },
            loadExistingIngredients: function () {
                // 获取隐藏字段中的配料数据
                var ingredientDetailsText = $('#c-ingredient_details').val();
                console.log('原始配料数据:', ingredientDetailsText);
                console.log('数据类型:', typeof ingredientDetailsText);
                
                if (ingredientDetailsText && ingredientDetailsText.trim() !== '') {
                    try {
                        // 如果数据已经是对象，直接使用
                        var ingredientsObj;
                        if (typeof ingredientDetailsText === 'object') {
                            ingredientsObj = ingredientDetailsText;
                        } else {
                            ingredientsObj = JSON.parse(ingredientDetailsText);
                        }
                        console.log('解析后的配料对象:', ingredientsObj);
                        console.log('配料对象类型:', typeof ingredientsObj);
                        
                        // 清空容器
                        $('#ingredient-container').empty();
                        
                        // 为每个配料创建行
                        var index = 0;
                        console.log('开始遍历配料对象，总共有', Object.keys(ingredientsObj).length, '个配料');
                        
                        for (var ingredientId in ingredientsObj) {
                            if (ingredientsObj.hasOwnProperty(ingredientId)) {
                                var quantity = ingredientsObj[ingredientId];
                                console.log('处理配料 [索引:', index, ']:', ingredientId, '数量:', quantity);
                                
                                // 通过配料名称获取对应的ID
                                $.ajax({
                                    url: 'clothmaking_raw/getRawInfo',
                                    type: 'GET',
                                    data: {
                                        searchKey: 'name',
                                        keyValue: ingredientId
                                    },
                                    async: false, // 同步请求，确保获取到ID后再创建行
                                    success: function(response) {
                                        if (response && response.rows && response.rows.length > 0) {
                                            var ingredientData = response.rows[0];
                                            var ingredientIdValue = ingredientData.id;
                                            console.log('获取到配料ID [索引:', index, ']:', ingredientId, 'ID:', ingredientIdValue);
                                            
                                            var newRow = `
                                                <div class="row ingredient-row" style="margin-top: 10px;" data-ingredient-id="${ingredientId}">
                                                    <div class="col-xs-12 col-sm-5">
                                                        <input data-rule="required" data-source="clothmaking_raw/getRawInfo" data-field="name" class="form-control selectpage" name="row[ingredients][${index}][id]" type="text" value="${ingredientIdValue}">
                                                    </div>
                                                    <div class="col-xs-12 col-sm-5">
                                                        <input data-rule="required" class="form-control" name="row[ingredients][${index}][quantity]" type="number" value="${quantity}" min="0" step="0.01">
                                                    </div>
                                                    <div class="col-xs-12 col-sm-2">
                                                        <button type="button" class="btn btn-danger btn-sm remove-ingredient-btn">
                                                            <i class="fa fa-minus"></i> 删除
                                                        </button>
                                                    </div>
                                                </div>
                                            `;
                                            $('#ingredient-container').append(newRow);
                                            console.log('已添加配料行 [索引:', index, ']:', ingredientId, 'ID:', ingredientIdValue);
                                        } else {
                                            console.log('未找到配料ID [索引:', index, ']:', ingredientId);
                                            // 如果没找到ID，使用默认值
                                            var newRow = `
                                                <div class="row ingredient-row" style="margin-top: 10px;" data-ingredient-id="${ingredientId}">
                                                    <div class="col-xs-12 col-sm-5">
                                                        <input data-rule="required" data-source="clothmaking_raw/getRawInfo" data-field="name" class="form-control selectpage" name="row[ingredients][${index}][id]" type="text" value="">
                                                    </div>
                                                    <div class="col-xs-12 col-sm-5">
                                                        <input data-rule="required" class="form-control" name="row[ingredients][${index}][quantity]" type="number" value="${quantity}" min="0" step="0.01">
                                                    </div>
                                                    <div class="col-xs-12 col-sm-2">
                                                        <button type="button" class="btn btn-danger btn-sm remove-ingredient-btn">
                                                            <i class="fa fa-minus"></i> 删除
                                                        </button>
                                                    </div>
                                                </div>
                                            `;
                                            $('#ingredient-container').append(newRow);
                                            console.log('已添加配料行 [索引:', index, '] (无ID):', ingredientId);
                                        }
                                    },
                                    error: function(xhr, status, error) {
                                        console.error('获取配料ID失败 [索引:', index, ']:', error);
                                        // 请求失败时，使用默认值
                                        var newRow = `
                                            <div class="row ingredient-row" style="margin-top: 10px;" data-ingredient-id="${ingredientId}">
                                                <div class="col-xs-12 col-sm-5">
                                                    <input data-rule="required" data-source="clothmaking_raw/getRawInfo" data-field="name" class="form-control selectpage" name="row[ingredients][${index}][id]" type="text" value="">
                                                </div>
                                                <div class="col-xs-12 col-sm-5">
                                                    <input data-rule="required" class="form-control" name="row[ingredients][${index}][quantity]" type="number" value="${quantity}" min="0" step="0.01">
                                                </div>
                                                <div class="col-xs-12 col-sm-2">
                                                    <button type="button" class="btn btn-danger btn-sm remove-ingredient-btn">
                                                        <i class="fa fa-minus"></i> 删除
                                                    </button>
                                                </div>
                                            </div>
                                        `;
                                        $('#ingredient-container').append(newRow);
                                        console.log('已添加配料行 [索引:', index, '] (请求失败):', ingredientId);
                                    }
                                });
                                
                                index++;
                            }
                        }
                        
                        // 将JSON中的配料数据转换为selectpage格式
                        var selectPageData = [];
                        for (var ingredientName in ingredientsObj) {
                            if (ingredientsObj.hasOwnProperty(ingredientName)) {
                                selectPageData.push({
                                    id: ingredientName,
                                    name: ingredientName
                                });
                            }
                        }
                        console.log('转换后的selectpage数据:', selectPageData);
                        
                        // 初始化所有selectpage并设置数据
                        $('#ingredient-container .selectpage').each(function(index) {
                            var $this = $(this);
                            
                            require(['selectpage'], function() {
                                $this.selectPage({
                                    eAjaxSuccess: function(data) {
                                        data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                                        data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                                        return data;
                                    }
                                });
                                
                                // 设置配料数据
                                $this.selectPageData(selectPageData);
                                console.log('已设置配料数据到selectpage [行索引:', index, ']');
                            });
                        });
                        
                        console.log('配料行创建完成，总共创建了', index, '行');
                        console.log('配料数据加载完成');
                    } catch (e) {
                        console.error('解析配料数据失败:', e);
                        console.error('错误详情:', e.message);
                        console.error('原始数据:', ingredientDetailsText);
                        Toastr.error('加载配料数据失败: ' + e.message);
                    }
                } else {
                    console.log('没有找到配料数据或数据为空');
                }
            },
            bindIngredientEvent: function () {
                // 绑定添加配料按钮事件
                $(document).on('click', '.add-ingredient-btn', function () {
                    var container = $('#ingredient-container');
                    var rowCount = container.find('.ingredient-row').length;
                    var newRow = `
                        <div class="row ingredient-row" style="margin-top: 10px;">
                            <div class="col-xs-12 col-sm-5">
                                <input data-rule="required" data-source="/aNVxAODluZ.php/clothmaking_raw/getRawInfo" data-field="name" class="form-control selectpage" name="row[ingredients][${rowCount}][id]" type="text" value="">
                            </div>
                            <div class="col-xs-12 col-sm-5">
                                <input data-rule="required" class="form-control" name="row[ingredients][${rowCount}][quantity]" type="number" value="" min="0" step="0.01">
                            </div>
                            <div class="col-xs-12 col-sm-2">
                                <button type="button" class="btn btn-danger btn-sm remove-ingredient-btn">
                                    <i class="fa fa-minus"></i> 删除
                                </button>
                            </div>
                        </div>
                    `;
                    container.append(newRow);
                    
                    // 重新初始化新添加的selectpage
                    var newSelectPage = container.find('.ingredient-row:last-child .selectpage');
                    require(['selectpage'], function() {
                        newSelectPage.selectPage({
                            eAjaxSuccess: function(data) {
                                data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                                data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                                return data;
                            }
                        });
                    });
                });
                
                // 绑定删除配料按钮事件
                $(document).on('click', '.remove-ingredient-btn', function () {
                    $(this).closest('.ingredient-row').remove();
                    // 重新排序name属性
                    $('#ingredient-container .ingredient-row').each(function(index) {
                        $(this).find('input[name*="[id]"]').attr('name', `row[ingredients][${index}][id]`);
                        $(this).find('input[name*="[quantity]"]').attr('name', `row[ingredients][${index}][quantity]`);
                    });
                });
                

            }
        }
    };
    return Controller;
});
